<template>
  <div class="register-page">
    <div class="register-page__wrap">
      <div class="register-box">
        <h3 class="register-box__title">注册</h3>
        <a-form
          ref="formRef"
          class="register-box__form"
          :model="formState"
          :rules="rules"
          :label-col="{ span: 4 }"
        >
          <a-form-item label="手机号" name="phone">
            <a-input
              type="string"
              v-model:value="formState.phone"
              placeholder="请输入手机号"
            ></a-input>
          </a-form-item>
          <a-form-item label="密码" name="password">
            <a-input
              type="password"
              v-model:value="formState.password"
              placeholder="请输入密码"
            ></a-input>
          </a-form-item>
          <a-form-item label="确认密码" name="_password">
            <a-input
              type="password"
              v-model:value="formState._password"
              placeholder="请再次输入密码"
            ></a-input>
          </a-form-item>
          <a-form-item label="性别" name="gender">
            <a-radio-group v-model:value="formState.gender">
              <a-radio :value="0">女</a-radio>
              <a-radio :value="1">男</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="昵称" name="nickname">
            <a-input
              type="string"
              v-model:value="formState.nickname"
              placeholder="请输入昵称"
            ></a-input>
          </a-form-item>
          <a-flex justify="center">
            <a-button type="primary" @click="registerFun" :loading="loading">注册</a-button>
          </a-flex>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { userRegister } from '@/api/register';
import type { IUserInfo } from '@/interface/user';
import type { FormInstance } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const formRef = ref<FormInstance>();
const loading = ref(false);

const formState = reactive<IUserInfo>({
  phone: '',
  password: '',
  _password: '',
  gender: 0,
  nickname: '',
});

// 手机号验证规则
const validatePhone = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject(new Error('请输入手机号'));
  }
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(value)) {
    return Promise.reject(new Error('请输入正确的手机号格式'));
  }
  return Promise.resolve();
};

// 密码验证规则
const validatePassword = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject(new Error('请输入密码'));
  }
  if (value.length < 6) {
    return Promise.reject(new Error('密码长度不能少于6位'));
  }
  if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(value)) {
    return Promise.reject(new Error('密码必须包含字母和数字'));
  }
  return Promise.resolve();
};

// 确认密码验证规则
const validateConfirmPassword = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject(new Error('请确认密码'));
  }
  if (value !== formState.password) {
    return Promise.reject(new Error('两次输入的密码不一致'));
  }
  return Promise.resolve();
};

// 昵称验证规则
const validateNickname = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject(new Error('请输入昵称'));
  }
  if (value.length < 2 || value.length > 20) {
    return Promise.reject(new Error('昵称长度应在2-20个字符之间'));
  }
  return Promise.resolve();
};

// 性别验证规则
const validateGender = async (_rule: Rule, value: number) => {
  if (value === undefined || value === null) {
    return Promise.reject(new Error('请选择性别'));
  }
  return Promise.resolve();
};

// 表单验证规则
const rules: Record<string, Rule[]> = {
  phone: [{ validator: validatePhone, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  _password: [{ validator: validateConfirmPassword, trigger: 'blur' }],
  gender: [{ validator: validateGender, trigger: 'change' }],
  nickname: [{ validator: validateNickname, trigger: 'blur' }],
};

const registerFun = async () => {
  try {
    // 验证表单
    await formRef.value?.validate();

    loading.value = true;
    console.log(formState);
    const res = await userRegister(formState);
    if ((res as any).code === 0) {
      message.success('注册成功');
      router.replace({
        path: '/login',
      });
    }
  } catch (error) {
    console.log('验证失败或注册失败:', error);
    if (error && typeof error === 'object' && 'errorFields' in error) {
      // 表单验证失败
      message.error('请检查表单填写是否正确');
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="less" scoped>
.register-page,
.register-page__wrap {
  width: 100%;
  height: 100%;
}

.register-page__wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  min-height: 100vh;
}

.register-box {
  width: 450px;
  padding: 32px;
  background: white;
  border: none;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);

  &__title {
    text-align: center;
    margin: 0 0 32px 0;
    font-size: 28px;
    font-weight: 600;
    color: #1e293b;
  }

  &__form {
    .ant-form-item {
      margin-bottom: 24px;

      :deep(.ant-form-item-label) {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }

    .ant-input {
      height: 44px;
      border-radius: 8px;
      border: 1px solid #e2e8f0;
      transition: all 0.2s ease;

      &:focus,
      &:hover {
        border-color: #667eea;
        box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
      }
    }

    .ant-btn-primary {
      border-radius: 8px;
      background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
      border: none;
      font-weight: 500;
      box-shadow: 0 4px 12px rgba(118, 75, 162, 0.3);
      transition: all 0.2s ease;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 6px 16px rgba(118, 75, 162, 0.4);
      }

      &:active {
        transform: translateY(0);
      }
    }

    .ant-btn-link {
      color: #64748b;
      transition: all 0.2s ease;

      &:hover {
        color: #667eea;
      }
    }
  }
}
</style>
